<template>
    <div>
        <el-form
            ref="formRef"
            :model="formData"
            label-width="100px"
            :size="'default'"
            status-icon
            :inline="true"
            class="query-filter"
        >
            <el-form-item label="堆场" prop="cfs_cod">
                <el-select
                    v-model="formData.cfs_cod"
                    :clearable="true"
                    filterable
                    placeholder="Select"
                    width="200px"
                >
                    <el-option
                        v-for="optValue in cyCfs"
                        :key="optValue.value"
                        :label="optValue.label"
                        :value="optValue.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="时间段">
                <el-date-picker
                    v-model="formData.rangeDate"
                    type="monthrange"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始月份"
                    end-placeholder="截止月份"
                    :shortcuts="shortcuts"
                />
            </el-form-item>
        </el-form>
        <el-table
            id="cfsfeereport-table-cfsfeereport"
            ref="tableRef"
            :data="tableData"
            v-bind="tableDefaultAttribute"
            row-key="id"
            :max-height="tableHeight"
            table-layout="auto"
            :summary-method="showSummaries"
            show-summary
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column type="selection" width="75" :align="'center'" />
            <template v-for="col in tableColumns" :key="col.prop">
                <el-table-column
                    v-if="!col.isHidden"
                    :align="col.align"
                    :prop="col.prop"
                    :label="col.label"
                    :formatter="col.formatter"
                    :type="col.type"
                    :fixed="col.fixed"
                    :width="col.width"
                >
                </el-table-column>
            </template>
        </el-table>
        <el-button-group class="bg">
            <el-space>
                <NormalBtn
                    @click="onQuery"
                    :text="'生成场站费用报表'"
                ></NormalBtn>
                <el-dropdown @command="handleCommand">
                    <el-button type="primary" class="btn">
                        导出 Excel<el-icon class="el-icon--right"
                            ><arrow-down
                        /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="current"
                                >当前页</el-dropdown-item
                            >
                            <el-dropdown-item command="all"
                                >全部</el-dropdown-item
                            >
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-space>
        </el-button-group>
        <div class="page">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[50, 100, 150, 200]"
                layout="sizes, prev, pager, next, total"
                :total="totalnum"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
    <el-dialog
        v-model="dialogProsessVisible"
        title="导出"
        draggable
        destroy-on-close
        :center="true"
        width="90%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
    >
        <Progress :percent="paramData"> </Progress>
    </el-dialog>
</template>
<script setup lang="ts" name="CfsFeeReport">
import { ref, onMounted } from 'vue';
import { Request } from '@/app/request';
import { useAppStore } from '@/store/app';
import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';
import { ElMessage, TableInstance } from 'element-plus';
import type { TableColumnCtx } from 'element-plus'
import { TableColumn } from '@/common/types/app';
import {
    tableColumnDefault,
    tableDefaultAttribute,
    useTableInfo,
} from '@/hooks/useTable';
import { exportExcel, formatDate, transFormatter } from '@/common/tools';
import { CfsFeeReportModel } from '@/common/types/business';
import { tableMaxHeightAdjust } from '@/common/const';
import Progress from '@/components/forms/Progress.vue';
import { ColOpt } from '@/common/types/report';
import { shortcuts } from '@/common/const';
interface SummaryMethodProps<T = CfsFeeReportModel> {
  columns: TableColumnCtx<T extends CfsFeeReportModel? T: any>[]
  data: T[]
}
const formData = ref<{ cfs_cod?: number; rangeDate: string }>({
    rangeDate: '',
});
const tableRef = ref<TableInstance>();
const tableHeight = ref(600);
const tableData = ref<Array<CfsFeeReportModel>>([]);
const { feecod, cyCfs } = storeToRefs(useAppStore());
const dialogProsessVisible = ref(false);
const paramData = ref(0);
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'out_cfs') {
        data = cyCfs.value;
    } else if (column['property'] === 'cal_days') {
        return Math.round(parseInt(cellValue)).toString();
    } else if (column['property'] === 'stack_days') {
        return Math.round(parseInt(cellValue)).toString();
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const initTableColumns = [
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr',
        label: '箱号',
        sortable: true,
        formFieldItemType: 'input',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'cntr_siz_cod',
        label: '尺寸',
        sortable: true,
        formFieldItemType: 'input',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'cntr_typ_cod',
        label: '箱型',
        sortable: true,
        formFieldItemType: 'input',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'in_cfs_tim',
        label: '进场日期',
        sortable: true,
        formatter: formatDate,
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'out_cfs_tim',
        label: '出场日期',
        sortable: true,
        formatter: formatDate,
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'stack_days',
        label: '堆存天数',
        sortable: false,
        formatter: onFormatter,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'cal_days',
        label: '计费天数',
        sortable: false,
        formatter: onFormatter,
        width: 200,
    },
];
const tableColumns = ref<TableColumn[]>([]);

const initColumns = (colOpts: Array<ColOpt>) => {
    // [ { fee_cod: '0105', currency_cod: 'USD' } ]
    tableColumns.value.length = 0;
    //tableColumns.value = initTableColumns;
    for (let index = 0; index < initTableColumns.length; index++) {
        const element = initTableColumns[index];
        tableColumns.value.push(element);
    }
    // tableData.value.length = 0;
    const insertColumnNum = 7;
    for (let index = 0; index < colOpts.length; index++) {
        const element = colOpts[index];
        const feeName = transFormatter(element.fee_cod, feecod.value);
        tableColumns.value.splice(insertColumnNum + index, 0, {
            ...tableColumnDefault,
            order: insertColumnNum + index,
            prop: `${element.currency_cod}${element.fee_cod}`,
            label: `${feeName}(${element.currency_cod})`,
            formFieldItemType: 'input',
            width: 150,
        });
    }
};
const summary: Array<string> = [];
onMounted( () => {
    for (let index = 0; index < initTableColumns.length; index++) {
        const element = initTableColumns[index];
        tableColumns.value.push(element);
    }
    tableHeight.value = window.innerHeight - tableMaxHeightAdjust - 70;
});
const getData = async () => {
    if (formData.value.rangeDate.length !== 2) {
        ElMessage.info('请选择时间段');
        return undefined;
    }
    // console.log(formData.value.rangeDate[1]);
    const param = {
        start_tim: formData.value.rangeDate[0],
        end_tim: dayjs(formData.value.rangeDate[1]).endOf('month').toDate(),
        fee_owner: formData.value.cfs_cod,
    };
    const req = new Request('生成场站费用报表', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        ...param,
    });
    const r = await req.post();
    return r;
};
const showSummaries = (param: SummaryMethodProps) => {
    if (Math.ceil(totalnum.value / pageSize.value) >= currentPage.value) {
        return summary;
    } else {
        return [];
    }
};
const onRefresh = async () => {
    const r = await getData();

    if (r && r.code > 100) {
        if (currentPage.value === 1) {
            initColumns(r.ext.columnOpt);
        }
        if (r.ext.total) {
            totalnum.value = parseInt(r.ext.total);
        }
        if (r.ext.sum) {
            summary.length = 0;
            summary[1] = '合计:';
            for (const key in r.ext.sum) {
                // eslint-disable-next-line no-prototype-builtins
                if (r.ext.sum.hasOwnProperty(key)) {
                    const findIndex = tableColumns.value.findIndex((col) => col.prop === key);
                    if (findIndex > -1) {
                        summary[findIndex + 1] = r.ext.sum[key];
                    }
                    
                }
            }
            // console.log(tableColumns.value);
            
            // console.log(summary);
            
        }
        tableData.value.length = 0;
        tableData.value = r.obj;
    }
};
const exportAll = async () => {
    if (totalnum.value <= 0) {
        ElMessage.info('请先生成报表数据');
        return;
    }
    const pages = Math.ceil(totalnum.value / pageSize.value);
    dialogProsessVisible.value = true;
    for (let index = 1; index <= pages; index++) {
        currentPage.value = index;
        paramData.value = Math.round((index / pages) * 100);
        const r = await getData();
        if (r && r.code > 100) {
            tableData.value.push(...r.obj);
        }
    }
    dialogProsessVisible.value = false;
    exportExcel(`${tableRef.value!.$el.id}`);
    currentPage.value = 1;
    onRefresh();
};

const onQuery = async () => {
    currentPage.value = 1;
    totalnum.value = 0;
    await onRefresh();
    // 动态调整表格字段
};
const {
    currentPage,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
} = useTableInfo(onRefresh);
const handleCommand = async (command: string | number | object) => {
    if (command === 'current') {
        exportExcel(`${tableRef.value!.$el.id}`);
    } else {
        await exportAll();
    }
};
</script>
<style lang="scss" scoped>
.query-filter {
    margin-bottom: 20px;
    padding: 10px;
    border: solid 2px var(--el-color-primary);
}
.query-filter .el-select {
    --el-select-width: 220px;
}
.query-filter .el-form-item {
    margin-bottom: 0px;
}
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
.page {
    float: right;
    margin-top: 10px;
}
</style>
